import router from "./index";
import store from "../store";
import { Message } from "element-ui";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { getToken, getMation } from "@/utils/auth";
import jwt_decode from "jwt-decode";
NProgress.configure({ showSpinner: false });

const whiteList = [
    "/login",
    "/home",
    "/falvfk",
    "/hyzixun",
    "/hyzx/flfg",
    "/hyzx/rwzf",
    "/details",
    "/register",
    "/retrieve",
    "/news/list",
    "/jssggHome",
    "/jsgg/guanyuxh",
    "/jsgg/hyzixun",
    "/jsgg/dec",
    "/about",
    "/gxzd/home",
    "/jiangxiang",
    "/jxdec",
    "/zypx",
    "/hyzc",
    "/video",
    "/video/dec",
    "/zpzs",
    "/hyzc/dec",
]; // 白名单

router.beforeEach(async (to, from, next) => {
    // 路由加载进度条
    NProgress.start();
    const hasToken = getToken();
    const hasMation = getMation();
    if (hasToken) {
        if (to.path === "/login") {
            next({ path: "/" });
            NProgress.done();
        } else {
            // 这里 需要设定 一个专有的 字段 用来判断 vuex 里面的数据是否 被清空
            //如果被清空了，重新调取接口获取数据
            const hasGetUserInfo = store.getters.name;
            if (hasGetUserInfo) {
                next();
            } else {
                const data = {
                    token: hasToken,
                };
                // const user = jwt_decode(hasToken)
                try {
                    await store.dispatch("user/getInfo");
                    next();
                } catch (error) {
                    await store.dispatch("user/resetToken");
                    next(
                        `/login?redirect=${to.path}&query=${JSON.stringify(
                            to.query
                        )}`
                    );
                    NProgress.done();
                }
            }
        }
    } else {
        if (hasMation) {
            await store.dispatch("user/login", JSON.parse(hasMation));
            next();
        } else {
            /* has no token*/
            if (whiteList.indexOf(to.path) !== -1) {
                // in the free login whitelist, go directly
                next();
            } else {
                // other pages that do not have permission to access are redirected to the login page.
                next(
                    `/login?redirect=${to.path}&query=${JSON.stringify(
                        to.query
                    )}`
                );
                NProgress.done();
            }
        }
    }
});

router.afterEach(() => {
    // finish progress bar
    NProgress.done();
});
